﻿using ReprojectWebMercator.Modules.glslNoise;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReprojectWebMercator.Samples
{
    internal class cloudFrag : GLSLFuncBase
    {
        public sampler2D uTxtShape;
        public sampler2D uTxtCloudNoise;
        float uTime;

        float uFac1= 17.8f;
        float uFac2= 2.7f;
        float uTimeFactor1= 0.002f;
        float uTimeFactor2= 0.0015f;
        float uDisplStrenght1= 0.04f;
        float uDisplStrenght2=0.08f;

        private glslNoise3d noise = new glslNoise3d();

        vec4 gammaCorrect(vec4 color, float gamma)
        {
            return pow(color, vec4(1.0 / gamma));
        }

        vec4 levelRange(vec4 color, float minInput, float maxInput)
        {
            return min(max(color - vec4(minInput), vec4(0.0)) / (vec4(maxInput) - vec4(minInput)), vec4(1.0));
        }

        vec4 levels(vec4 color, float minInput, float gamma, float maxInput)
        {
            return gammaCorrect(levelRange(color, minInput, maxInput), gamma);
        }
        public override vec4 PixelPassMain(vec2 vUv)
        {
            vec2 newUv = vUv;

            vec4 txtNoise1 = texture2D(uTxtCloudNoise, vec2(vUv.x + uTime * 0.0001, vUv.y - uTime * 0.00014)); // noise txt
            vec4 txtNoise2 = texture2D(uTxtCloudNoise, vec2(vUv.x - uTime * 0.00002, vUv.y + uTime * 0.000017 + 0.2)); // noise txt

            float noiseBig = noise.fbm3d(vec3(vUv * uFac1, uTime * uTimeFactor1), 1) +  0.5f;
            newUv += noiseBig * uDisplStrenght1;

            float noiseSmall = noise.snoise(vec3(newUv * uFac2, uTime * uTimeFactor2));
            newUv += noiseSmall * uDisplStrenght2;

            vec4 txtShape = texture2D(uTxtShape, newUv);
            
            float alpha = levels((txtNoise1 + txtNoise2) * 0.6, 0.2f, 0.4f, 0.7f).r;
            //return new ReprojectWebMercator.vec4(alpha, alpha, alpha, 1); 
            alpha *= txtShape.r;

            var b1 = vec4(0.95, 0.95 , 0.95 , alpha) ;

            var b2 = new vec4(48/255.0, 104/255.0, 172/255.0, 1);

            var gl_FragColor = new vec4(b1.x * b1.w + b2.x * (1 - b1.w),
                b1.y * b1.w + b2.y * (1 - b1.w),
                b1.z * b1.w + b2.z * (1 - b1.w),
                b1.w * b1.w + b2.w * (1 - b1.w));

            return gl_FragColor;
        }
    }
}
